package com.market.plus.controller.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.market.plus.core.dto.AlbumDto;
import com.market.plus.core.service.ParticipantService;

@Component("albumValidator")
public class AlbumValidator implements Validator {

   private ParticipantService participantService;

   public boolean supports(Class<?> album) {
      return AlbumDto.class.isAssignableFrom(album);
   }

   public void validate(Object object, Errors errors) {
      validateObject(object, errors);
   }

   public void validateObject(Object object, Errors errors) {
      AlbumDto album = (AlbumDto) object;
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "err.required");
      if (!errors.hasFieldErrors("name")) {
         if (this.participantService.hasAlbumNameExist(album.getParticipantId(), album.getName())) {
            errors.rejectValue("name", "err.unique");
         }
      }
   }

   public void setParticipantService(ParticipantService participantService) {
      this.participantService = participantService;
   }

   public ParticipantService getParticipantService() {
      return participantService;
   }
}
